package com.tanhua.dubbo.server.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.TaoHuavo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;


@Service(version = "1.0.0")
@Slf4j
public class TaoHuaApiImpl implements TaoHuaApi {




    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;
    @Autowired
    private RedisTemplate redisTemplate;



    public static final String HQ_KEY_PREFIX = "HQ_TIMES_";


    @Override
    public Boolean saveSound(Sound sound) {

        try {
            //校验(保证2个东西都存在)
            if(!ObjectUtil.isAllNotEmpty(sound.getUserId(), sound.getSouUrl())){
                return false;
            }

            Long times = getTimes(sound);

            if (times >= 10){
                return false;
            }
            //设置id
            sound.setId(ObjectId.get());
            sound.setDate(System.currentTimeMillis());

            Long sid = idService.createId(IdType.SOUND);

            sound.setSid(sid);


            //保存到Mongodb中
            this.mongoTemplate.save(sound);

            return true;
        } catch (Exception e) {
            log.error("桃花语音发布失败~ sound = " + sound, e);
        }
        return false;
    }

        @Override
        public Long getTimes(Sound sound) {
            //查询访客用户在今天是否已经记录过的次数
            String today = DateUtil.today();
            Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
            Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();

            Query query = Query.query(Criteria.where("userId").is(sound.getUserId())
                    .andOperator(Criteria.where("date").gte(minDate),
                            Criteria.where("date").lte(maxDate)
                    )
        );
        long count = this.mongoTemplate.count(query, Sound.class);
        return count;
    }

    @Override
    public TaoHuavo getSound(Long userId) {
        ArrayList<Long> sids = new ArrayList<>();

        Query query = Query.query(Criteria.where("userId").ne(userId));
        List<Sound> sounds = this.mongoTemplate.find(query, Sound.class);

        for (Sound sound : sounds) {
            sids.add(sound.getSid());
        }
        Random random = new Random();
        int a = sids.size();
        int nextInt = random.nextInt(a);


        String redisKey = this.getkeys(userId);

        String hashKey = String.valueOf(sids.get(nextInt));
        //获取所有的key
        Set keys = this.redisTemplate.opsForHash().keys(redisKey);
        //key的数量为10时 直接结束
        int min = Math.min(10, a);
        if (keys.size() >= min){
            return null;
        }

        Integer count = 9 - keys.size();


        //出现重复key 则重新执行一遍
        if (redisTemplate.opsForHash().hasKey(redisKey,hashKey)){
            this.getSound(userId);
        }
        //在redis中保存一条
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");


        Query query2 = Query.query(Criteria.where("sid").ne(sids.get(nextInt)));
        Sound one = this.mongoTemplate.findOne(query2, Sound.class);

        TaoHuavo taoHuavo = new TaoHuavo();

        taoHuavo.setRemainingTimes(count);
        taoHuavo.setSoundUrl(one.getSouUrl());
        taoHuavo.setUserid(one.getUserId());

        return taoHuavo;
    }


    private String getkeys(Long userId){
        //设置redis的key 利用当天时间来保证一天中的获取
        String today = DateUtil.today();
        return HQ_KEY_PREFIX + today+userId;
    }

}
